#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import cgi
import urllib
import os

import webapp2
import jinja2
from google.appengine.ext import db

jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class Registration(db.Model):
    """Data for a registration entry."""
    name = db.StringProperty()  # user-readable name for this entry/Luna
#    id = db.StringProperty()    # unique ID for this entry/Luna (changed to Key Name)
    ip = db.StringProperty()    # external IP address to use for connections
    port = db.IntegerProperty()  # external port # to use for connections
    duration = db.IntegerProperty() # how long this entry should last. default is ???
    date = db.DateTimeProperty(auto_now_add=True) # date and time this entry was added/updated
    

def registrar_key(registrar_name=None):
    return db.Key.from_path('Registration', registrar_name or 'default_registrar')
    

class MainHandler(webapp2.RequestHandler):

    def get(self):        
        self.response.out.write('<html><body>')
        registrar_name = self.request.get('registrar_name')
        #if not registrar_name:
        #    registrar_name = 'default_registrar'
        
        lunas = db.GqlQuery("SELECT * FROM Registration WHERE ANCESTOR IS :1 ORDER BY date DESC LIMIT 10",
            registrar_key(registrar_name))
            
        # using jinja template system
        template_values = {
            'lunas': lunas    
        }
        template = jinja_env.get_template('index.html')
        self.response.out.write(template.render(template_values))
        
#        for luna in lunas:
#            if luna.name:
#                self.response.write('<b>%s</b>' % (luna.name))
#            else:
#                self.response.write('Unnamed Luna')
#            self.response.write(' added at %s' % luna.date)
#            self.response.write('<br />')
#        self.response.write('<br />')
            
#        self.response.out.write("""
#            <form action="/add?%s" method="post">
#                <div>Name:<input name="name"></input></div>
#                <div>ID:<input name="id"></input></div>
#                <div>IP:<input name="ip"></input></div>
#                <div>Port<input name="port"></input></div>
#                <div>Duration:<input name="duration"></input></div>
#                <div><input type="submit" value="add"></input></div>
#            </form>
#            </body>
#         </html>
#        """ % (urllib.urlencode({'registrar_name':registrar_name or 'default_registrar'})) )
                

class AddLuna(webapp2.RequestHandler):

    def post(self):
        # create a new record with the proper parent
        registrar_name = self.request.get('registar_name')
        id = self.request.get('id')
        
        reg_key = db.Key.from_path('Registration', id)
        reg = db.get(reg_key)
        
        if reg is None:
            reg = Registration(key_name=id, parent=registrar_key(registrar_name))

        # set all the values to what was passed in
        reg.name = self.request.get('name')
        reg.ip = self.request.get('ip')
        reg.port = int(self.request.get('port'))
        reg.duration = int(self.request.get('duration'))
        
        # check the id to see if this has already been added. if so, this is an update call
#        found = db.GqlQuery("SELECT * FROM Registration WHERE ANCESTOR IS :1 AND id = :2",
#            registrar_key(registrar_name), reg.id)
            
        # store to db
        reg.put()
        
        # and then go back to main page
        self.redirect('/?' + urllib.urlencode({'registrar_name':registrar_name}))
        
         
#class XMLRPCHandler(webapp2.RequestHandler):
#
#    def post(self):
#        response, code = self.handleRequest(self.requestbody, self.HTTP_POST)
#        self.response.headers['Content-Type'] = 'application/xml'
#        self.response.set_status(code)
#        self.response.out.write(response)
        

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/add', AddLuna),
], debug=True)


#if __name__ == "__main__":
#    main()